--[[
 Attempts to identify a DVD, file or YouTube video

 $Id$

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]

--[[
References:
http://www.videolan.org/developers/vlc/share/lua/README.txt
http://www.lua.org/manual/5.1/manual.html
http://www.lua.org/pil/index.html
https://github.com/keplerproject/luarocks/blob/master/src/luarocks/cfg.lua (for identifying the Operating System)
http://dvdid.cjkey.org.uk/ (for the dvdid.exe executable)
http://msdn.microsoft.com/en-us/library/windows/desktop/dd376453(v=vs.85).aspx (info on the DirectShow IDvdInfo2::GetDiscID method)
http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes (for file hash)
--]]

require "simplexml"
require "dvdidhelp"

function read_meta()
	vlc.msg.dbg( "### VLC4DVX read_meta module" )
	if vlc.item:uri() then vlc.msg.dbg( "### VLC4DVX URI "..vlc.item:uri() ) end
	if vlc.item:name() then vlc.msg.dbg( "### VLC4DVX NAME "..vlc.item:name() ) end

	if string.match( string.sub( vlc.item:uri(), 1, 4 ), "dvd:" ) then
		vlc.msg.info( "### VLC4DVX: THIS IS A DVD" )

		local drive
		_,_,drive = string.find( vlc.item:uri(), "dvd:///(.+)$" )
		if drive then
			vlc.msg.dbg( "### VLC4DVX: DVD drive is "..drive )

			-- Is there a Volume Name?
			-- FIXME: Need to handle this differently for non-Windows OS
			local windowsDrive
			_,_,windowsDrive = string.find( drive, "(%w%:)") -- Just a letter, followed by a :
			vlc.msg.dbg( "### VLC4DVX: For Windows, DVD drive changed to "..windowsDrive )
			for line in io.popen("cmd.exe /c vol "..windowsDrive):lines() do
				_,_,volumeName = string.find( line, "Volume in drive %S+ is (.+)$")
				if volumeName then
					vlc.msg.info( "### VLC4DVX: volumeName is "..volumeName )
					vlc.item:set_meta("title", volumeName)				-- Use first guess of the Title
				end
			end

			-- Get the DVDid using the external dvdid.exe program
			-- FIXME: Need to handle this differently for non-Windows OS
			dvdidExecutable = "C:\\dvdid.exe"
			local dvdID = io.popen(dvdidExecutable.." "..windowsDrive):read("*l")

			if dvdID then
				vlc.msg.info( "### VLC4DVX: ***dvdID is "..dvdID )

				local dvdIDunmangled = dvdidhelp.unmangle( dvdID )

				if dvdIDunmangled ~= dvdID then
					dvdID = dvdIDunmangled
					vlc.msg.info( "### VLC4DVX: ***dvdID unmangled to "..dvdID )
				end

				vlc.item:set_meta("DVDid", dvdID)					-- This is our own metadata for DVDid, using the executable from http://dvdid.cjkey.org.uk/
				vlc.item:set_meta("track_id", dvdID)				-- "track_id" seems to exist within VLC, but possibly confused with "trackid"

				-- Movie lookup using DVDINFO:
				-- See http://www.dvdid.info/faq.php#f1r0
				dvdidInfoApi = "http://www.api.dvdid.info/"
				dvdidInfoApiKey = "9069d0e8b554bca3df1592c83c498c5cd0661c2e"
				dvdidInfoApiGetInfoMethod = "getInfo"

				local dvdidInfoURL = dvdidInfoApi..dvdidInfoApiKey.."/"..dvdidInfoApiGetInfoMethod.."/"..vlc.strings.encode_uri_component(dvdID).."/xml"

				vlc.msg.dbg( "### VLC4DVX: dvdidInfoURL "..dvdidInfoURL )
				local feed = simplexml.parse_url( dvdidInfoURL )
				if feed.name and ( feed.name == "error" ) then
					vlc.msg.dbg( "### VLC4DVX: feed.name ERROR "..feed.name )
					return
				elseif feed.name and ( feed.name == "queryResults" ) then
					for _, dvdidInfo in ipairs( feed.children ) do
						simplexml.add_name_maps( dvdidInfo )
						dvdidInfoTitle = dvdidInfo.children_map["effTitle"][1].children[1] or dvdidInfo.children_map["dvdTitle"][1].children[1]
						if dvdidInfoTitle then
							vlc.msg.dbg( "### VLC4DVX: dvdidInfo dvdTitle "..dvdidInfoTitle )
							vlc.item:set_meta("title", dvdidInfoTitle)				-- Use our best guess of the Title
						end

						-- It would be nice to have a simple table of equivalences here:
						--    titleTitle => album,
						--    director   => artist etc
						--
						dvdidInfoAlbum = dvdidInfo.children_map["titleTitle"][1].children[1]
						dvdidInfoArtist = dvdidInfo.children_map["director"][1].children[1]
						dvdidInfoYear = dvdidInfo.children_map["movieReleaseYear"][1].children[1]
						dvdidInfoGenre = dvdidInfo.children_map["genre"][1].children[1]
						dvdidInfoLanguage = dvdidInfo.children_map["language"][1].children[1]
						dvdidInfoPublisher = dvdidInfo.children_map["studio"][1].children[1]
						dvdidInfoDescription = dvdidInfo.children_map["synopsis"][1].children[1]
						dvdidInfoEncodedBy = dvdidInfo.children_map["dataProvider"][1].children[1]

						if dvdidInfoAlbum then vlc.item:set_meta("album", dvdidInfoAlbum) end
						if dvdidInfoArtist then vlc.item:set_meta("artist", dvdidInfoArtist) end
						if dvdidInfoYear then vlc.item:set_meta("date", dvdidInfoYear) end
						if dvdidInfoGenre then vlc.item:set_meta("genre", dvdidInfoGenre) end
						if dvdidInfoLanguage then vlc.item:set_meta("language", dvdidInfoLanguage) end
						if dvdidInfoPublisher then vlc.item:set_meta("publisher", dvdidInfoPublisher) end
						if dvdidInfoPublisher then vlc.item:set_meta("copyright", dvdidInfoPublisher) end
						if dvdidInfoDescription then vlc.item:set_meta("description", dvdidInfoDescription) end
						if dvdidInfoEncodedBy then vlc.item:set_meta("encoded_by", dvdidInfoEncodedBy) end
					end

					-- At this point, we can use the DVDid to do a lookup into DVX:

				end
			end
		end

	elseif string.match( string.sub( vlc.item:uri(), 1, 5 ), "file:" ) then
		vlc.msg.info( "### VLC4DVX: THIS IS A FILE" )

	elseif string.match( string.sub( vlc.item:uri(), 1, 23 ), "http://www.youtube.com/" ) then
		vlc.msg.info( "### VLC4DVX: THIS IS A YOUTUBE VIDEO" )

		-- No point in doing anything here, since the lua playlist function switches this URI for one from the YouTube page, which in turn ditches any meta data produced here
	end
end
